package com.practice.misc;

public class UTF8Validator {
	public boolean validate(byte[] str) {
		try {
			for (int i=0; i<str.length; i++) {
				if (str[i] < 0x80) continue;
				if ((str[i]>>5) == 6) {
					i = eat(str, i, 1);
				}
				else if ((str[i]>>4) == 14) {
					i = eat(str, i, 2);
				}
				else if ((str[i]>>3) == 30) {
					i = eat(str, i, 3);
				}
				else {
					return false;
				}
			}
			
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	private int eat(byte[] str, int i, int len) throws Exception {
		if (i + len >= str.length) throw new Exception();
		for (int j=1; j<=i; j++) {
			if ((str[j]>>6) != 3) throw new Exception();
		}
		return i+len;
	}
}
